
//
//  KYRefreshControl.swift
//  01-我的微博
//
//  Created by apple on 15/8/7.
//  Copyright © 2015年 KY. All rights reserved.
//

import UIKit

private let kRefreshPullOffset: CGFloat = -60


class KYRefreshControl: UIRefreshControl {
    
    // 重写结束刷新方法
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    
    
    override init() {
        super.init()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // KVO
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        

        if frame.origin.y > 0 {
            return
        }
        
        if refreshing {
            refreshView.startLoading()
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {

            refreshView.rotateFlag = true
            
        }else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag {

            refreshView.rotateFlag = false
        }
    }
    
    deinit{
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    private func setupUI() {
        
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        addSubview(refreshView)
        // 隐藏默认转轮
        tintColor = UIColor.clearColor()
        
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    
    //MARK: - 懒加载 View
    private lazy var refreshView: KYRefreshView = KYRefreshView.refreshView()
}

class KYRefreshView: UIView {
    
    /// 旋转标记
    private var rotateFlag = false {
        
        didSet {
            rotateTipIcon()
        }
    }
    
    
    @IBOutlet weak var loadingIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    ///箭头按钮
    @IBOutlet weak var tipIcon: UIImageView!
    /// 从 XIB 中加载视图
    class func refreshView() -> KYRefreshView {
        return NSBundle.mainBundle().loadNibNamed("KYRefreshView", owner: nil, options: nil).last as! KYRefreshView
    }
    
    /// 箭头旋转动画
    private func rotateTipIcon() {
        
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        
        UIView .animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform =  CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    /// 开始加载动画
    private func startLoading() {
        
        // 如果动画正在旋转 不再进行新动画
        if loadingIcon.layer.animationForKey("loading") != nil {
            return
        }
        
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = M_PI * 2
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        
        loadingIcon.layer.addAnimation(anim, forKey: "loading")
        
    }
    /// 停止加载动画
    private func stopLoading() {
        
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    }
}